package Hot100;

import java.util.ArrayList;
import java.util.List;

public class 螺旋矩阵 {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> result = new ArrayList<>();
        int count = 0;
        int total = matrix.length * matrix[0].length;
        int rowMin = 0, colMin = 0, rowMax = matrix[0].length - 1, colMax = matrix.length - 1;
        while (true) {
            if (colMin == colMax && colMax == rowMin && rowMin == rowMax) {
                result.add(matrix[colMax][rowMax]);
                return result;
            }
            for (int i = rowMin; i < rowMax; i++) {
                result.add(matrix[colMin][i]);
                if (++count >= total) return result;
            }
            for (int i = colMin; i < colMax; i++) {
                result.add(matrix[i][rowMax]);
                if (++count >= total) return result;
            }
            for (int i = rowMax; i > rowMin; i--) {
                result.add(matrix[colMax][i]);
                if (++count >= total) return result;
            }
            for (int i = colMax; i > colMin; i--) {
                result.add(matrix[i][rowMin]);
                if (++count >= total) return result;
            }
            colMin++;
            colMax--;
            rowMin++;
            rowMax--;
        }
    }
}
